<?php
// +----------------------------------------------------------------------

namespace app\user\model;

use think\Model as ThinkModel;
use app\user\model\Vip as VipModel;
use think\facade\Db;

/**
 * 资金流水模型
 * @package app\cms\model
 */
class Money extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'user_money';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 获取资金流水列表
     * @return array|mixed
     */
    public static function getList($map = [], $order = [], $paginate = 0)
    {
		if ($paginate == 0) $paginate = config('paginate');
        $data_list = self::view('user_money', true)
            ->view("user_vip", ['realname','mobile','group'], 'user_vip.member_id=user_money.uid', 'left')
            ->where($map)
            ->order($order)
            ->paginate($paginate);
        return $data_list;
    }
    /**
     * 保存资金变动记录
     * @return array|mixed
     */
    public static function moneyLog($uid = 0, $type = 1, $balance = 0, $second = 0, $realpay = 0, $remark = '')
    {
		if ($uid == 0) return false;
		if ($balance == 0 && $second == 0 && $realpay == 0) return false;
		
		$vip = VipModel::where('member_id', $uid)->find();
		if (!$vip) return false;
		
        $log = self::create([
			'uid' 		=> $uid,
			'type'		=> $type,
			'balance'	=> $balance,
			'second'	=> $second,
			'realpay'	=> $realpay,
			'money'		=> $vip['money'] + $balance,
			'money_se'	=> $vip['money_se'] + $second,
			'remark'	=> $remark,
		]);
		
		// 保存用户余额
		if ($balance != 0 || $second != 0){
			$vip->money = $vip['money'] + $balance;
			$vip->money_se = $vip['money_se'] + $second;
			$vip->save();
		}
		
		if (!$log) return false;
		return  $log->id;
    }
	/**
	 * 变动模式
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array|static
	 */
	public static function type($id = 99)
	{
		$types = [
			1 => '后台充值',
			2 => '订单退款',
			3 => '现金支付',
			4 => '商品下单',
		];
	    if ($id === 99) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
}
